package org.jmresler.sakila.email.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.security.GeneralSecurityException;

@Configuration
public class EmailConfiguration {

    private final String mailServerHost;
    private final String protocol;
    private final Integer port;
    private final String username;
    private final String password;
    private final String auth;
    private final String ttlsEnabled;


    public EmailConfiguration(
            @Value("${spring.mail.host}") String mailServerHost,
            @Value("${spring.mail.protocol}") String protocol,
            @Value("${spring.mail.port}") Integer port,
            @Value("${spring.mail.username}") String username,
            @Value("${spring.mail.password}") String password,
            @Value("${spring.mail.properties.mail.smtp.auth}") String auth,
            @Value("${spring.mail.properties.mail.smtp.starttls.enable}") String ttlsEnabled
    ) {
        this.mailServerHost = mailServerHost;
        this.protocol = protocol;
        this.port = port;
        this.username = username;
        this.password = password;
        this.auth = auth;
        this.ttlsEnabled = ttlsEnabled;
    }

    @Bean
    public JavaMailSender javaMailSender() throws GeneralSecurityException {
        var mailSender = new JavaMailSenderImpl();
        var props = mailSender.getJavaMailProperties();

        mailSender.setProtocol(protocol);
        mailSender.setHost(mailServerHost);
        mailSender.setPort(port);
        mailSender.setUsername(username);
        mailSender.setPassword(password);

        props.put("mail.transport.protocol", protocol);
        props.put("mail.smtp.auth", auth);
        props.put("mail.smtp.starttls.enable", ttlsEnabled);
        props.put("mail.debug", "true");

        return mailSender;
    }
}
